<?php
/*
 * Created on Sep 13, 2010
 *
 * To change the template for this generated file go to
 * Window - Preferences - PHPeclipse - PHP - Code Templates
 */
 
include_once("./configure/configure.php");		//--> global var
include_once './configure/ppsdk_include_path.inc';
include_once("customerSession.inc.php");
include_once("Smarty.class.php");				//--> out template
include_once("Common.php");
include_once("UploadFiles.php");				//--> UploadFiles
include_once ("Session.php");					//-- Session

require_once 'PayPal.php';
require_once 'PayPal/Profile/Handler/Array.php';
require_once 'PayPal/Profile/API.php';
require_once 'PayPal/Type/BasicAmountType.php';
require_once 'PayPal/Type/PaymentDetailsType.php';

require_once 'PayPal/Type/DoExpressCheckoutPaymentRequestType.php';
require_once 'PayPal/Type/DoExpressCheckoutPaymentRequestDetailsType.php';
require_once 'PayPal/Type/DoExpressCheckoutPaymentResponseType.php';

require_once 'paypal-app/SampleLogger.php';
require_once 'paypal-app/constants.inc.php';

include_once ("orders/OrdersAccount.php");				//-- for payment
include_once ("paypal-app/PaymentPro.php");				//-- for payment
include_once ("paypal-app/PaypalInfo.php");				//-- for payment

include_once ("CustomerDao.php");
include_once ("OrdersDao.php");
include_once ("AddressBookDao.php");				//-- for payment
include_once ("orders/OrdersInfo.php");				//-- for payment

include_once("Strings.php");						//--> String utils
include_once("orders/Cart.php");					//--> Cart
include_once("orders/CartProduct.php");				//--> Cart
include_once("orders/CartProductAttribute.php");	//--> Cart

include_once("CouponDomain.php");					//--> coupon domain

require_once('includeHttps.php');

session_start();
//define('PAYPAL_URL', 'https://www.' . ENVIRONMENT . '.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=');


$common 		= new Common();
$objSession		= new Session(DB_TAG_SYSTEM, SESSION_TABLE_NAME);	//-- session
$objCustomerDao = new CustomerDao();
$objOrdersDao 	= new OrdersDao();

$payment 		= new PaymentPro();
$objPaypalInfo	= new PaypalInfo();
$logger 		= new SampleLogger('checkoutFinish.php', PEAR_LOG_DEBUG);

$objStrings 	= new Strings();
$objCart 		= new Cart();		//--> Cart
$objOrdersInfo	= new OrdersInfo();

/*----- check session -----*/
$isLogin	= false;

if($objSession->exist()) {
	$isLogin	= true;
	
	$customerid = $objSession->getUserID();
	
	$customer = $common->getRow(DB_TAG_SYSTEM, "SELECT * FROM customers WHERE id =$customerid");
  		
	$objCustomerDao->setID($customerid);
	$objCustomerDao->setFirstName($customer['firstname']);
    $objCustomerDao->setLastName($customer['lastname']);
    $objCustomerDao->setEmail($customer['email']);
    $objCustomerDao->setTelephone($customer['telephone']);
    $objCustomerDao->setFax($customer['fax']);
    $objCustomerDao->setNewsletter($customer['newsletter']);
    $objCustomerDao->setPaypalEC($customer['paypal_ec']);
    $objCustomerDao->setPaypalPayerid($customer['paypal_payerid']);
    $objCustomerDao->setCountryid($customer['countryid']);
    $objCustomerDao->setAddressid($customer['default_address_id']);
}else{
	$location = HOME_URL . "/viewCart.php";
	
    header("Location: $location");
}


if(isset($_SESSION['ordersInfo'])){
	$objOrdersInfo = unserialize($_SESSION['ordersInfo']);
}else{
	$location = HOME_URL;
	
	header("Location: $location");
	exit;
}

if($_SESSION['cart']){
	$objCart = unserialize($_SESSION['cart']);
}else{
	$location = HOME_URL;
	
	header("Location: $location");
	exit;
}

if(isset($_SESSION['customerInfo'])){
	$objCustomer = unserialize($_SESSION['customerInfo']);
}

// orders has changed
if($objCart->getStatus() != Cart::STATUS_LOOKED){
	$location = 'checkout.php';
	
    header("Location: $location");
}

date_default_timezone_set('America/Los_Angeles');


$currency_cd		= 'USD';

$paymentResponse 	= '';
$paymentMethod		= '';

if($objOrdersInfo->getPaymentMethod() == OrdersInfo::EXPRESS_CHECKOUT){
	$paymentMethod = "Paypal";
	
	if(isset($_SESSION['paypalInfo'])){
		$objPaypalInfo = unserialize($_SESSION['paypalInfo']);
	}else{
		$location = 'checkout.php';
		
		header("Location: $location");
		exit;
	}
	
	$profile = $objPaypalInfo->getAPIProfile();
	if(!isset($profile) || empty($profile)){
		$location = 'checkout.php';
		
		header("Location: $location");
		
		exit;
	}
	
	$paymentType		= $objPaypalInfo->getPaymentType();
	$token 				= $objPaypalInfo->getToken();
	$payerID			= $objPaypalInfo->getPayerid();
	$currencyCodeType	= $objPaypalInfo->getCurrencyCodeType();
	
	
	$paymentAmount 		= $objOrdersInfo->getAccount()->getAllTotal();
	
	$ec_details =& PayPal::getType('DoExpressCheckoutPaymentRequestDetailsType');
	
	$ec_details->setToken($token);
	$ec_details->setPayerID($payerID);
	$ec_details->setPaymentAction($paymentType);
	
	$amt_type =& PayPal::getType('BasicAmountType');
	$amt_type->setattr('currencyID', $currencyCodeType);
	$amt_type->setval($paymentAmount, 'iso-8859-1');  
	
	$payment_details =& PayPal::getType('PaymentDetailsType');
	$payment_details->setOrderTotal($amt_type);
	
	$ec_details->setPaymentDetails($payment_details);
	
	$ec_request =& PayPal::getType('DoExpressCheckoutPaymentRequestType');
	$ec_request->setDoExpressCheckoutPaymentRequestDetails($ec_details);
	
	$caller =& PayPal::getCallerServices($profile);
	
	// Execute SOAP request
	$response = $caller->DoExpressCheckoutPayment($ec_request);
	// $display = print_r($response, true);
	$logger->_log('DoExpressCheckoutPayment response: '. print_r($response,true));
	
	$ack = $response->getAck();
	
	$logger->_log('Ack='.$ack);
	
	switch ($ack) {
	   case ACK_SUCCESS:
	   case ACK_SUCCESS_WITH_WARNING:
	      // Show HTML below
	      break;
	   
	   default:
	      $_SESSION['response'] =& $response;   
	      $logger->_log('DoExpressCheckoutPayment failed: ' . print_r($response, true));
	      $location = HOME_URL . "/lib/paypal-app/ApiError.php";
	      header("Location: $location");  
	}
	
	// Marshall data out of response
	$details 		= $response->getDoExpressCheckoutPaymentResponseDetails();
	$payment_info 	= $details->getPaymentInfo();
	$tran_ID 		= $payment_info->getTransactionID();
	$paymentStatus	= $payment_info->getPaymentStatus();
	$paymentType	= $payment_info->getPaymentType();
	
	
	$amt_obj		= $payment_info->getGrossAmount();
	$amt 			= $amt_obj->_value;
	$currency_cd 	= $amt_obj->_attributeValues['currencyID'];
	$display_amt 	= $currency_cd.' '.$amt;
	
	//echo '$paymentAmount = ' . $paymentAmount . '<br>';
	//echo '$tran_ID = ' . $tran_ID . '<br>';
	//echo '$display_amt = ' . $display_amt . '<br>';
	if ($paymentStatus == 'Pending') {
		$pending_reason = $payment_info->getPendingReason();
		$payment_status .= ' (' . $pending_reason . ')';
		
	}
	
	$paymentType = 'PayPal Express Checkout';
	
	$comments = $objOrdersInfo->getComments();
	if(!empty($comments)){
		$paymentResponse = "$comments\n";
	}
	
	$paymentResponse .= "Transaction ID: $tran_ID\n" . "Payment Type: $paymentType\nPayment Status: $paymentStatus $payment_status";
}else if($objOrdersInfo->getPaymentMethod() == OrdersInfo::DIRECT_PAYMENT){
	$paymentMethod = "Credit Card";
	
	if(isset($_SESSION['paypalInfo'])){
		$objPaypalInfo = unserialize($_SESSION['paypalInfo']);
	}
	
	$profile = $objPaypalInfo->getAPIProfile();
	
	if(!is_object($profile)){
		$profile = $payment->sessionStart3Tokens();
		
		$objPaypalInfo->setAPIProfile($profile);
		
		$_SESSION['paypalInfo'] = serialize($objPaypalInfo);
	}
	
	
	if(!isset($profile) || empty($profile)){
		$location = 'checkout.php';
	
		header("Location: $location");
		exit;
	}
	
	
	// Build our request from $_POST
	// $dp_request = new TransactionSearchRequestType();
	$dp_request =& PayPal::getType('DoDirectPaymentRequestType');
	if (PayPal::isError($dp_request)) {
	   $logger->_log('Error in request: '. print_r($dp_request, true));
	} else {
	   $logger->_log('Create request: '. print_r($dp_request, true));
	}
	
	$logger->_log('Initial request: '. print_r($dp_request, true));
	
	$objBillingAddress 	= $objOrdersInfo->getDeliveryAddress();
	
	/**
	 * Get posted request values
	 */
	$paymentType 		= 'Sale';
	$firstName 			= $objPaypalInfo->getCCFirstName();
	$lastName 			= $objPaypalInfo->getCCLastName();
	$creditCardType 	= $objPaypalInfo->getCCType();
	$creditCardNumber 	= $objPaypalInfo->getCCNumber();
	$expDateMonth 		= $objPaypalInfo->getCCExpiresMonth();
	// Month must be padded with leading zero
//	$padDateMonth = str_pad($expDateMonth, 2, '0', STR_PAD_LEFT);
	
	$expDateYear 	= $objPaypalInfo->getCCYear();
	$cvv2Number 	= $objPaypalInfo->getCCCheckCode();
	
	$address1 		= $objBillingAddress->getStreet();
	$address2 		= '';
	$city 			= $objBillingAddress->getCity();
	$state 			= $objBillingAddress->getState();
	$zip 			= $objBillingAddress->getZipcode();
	$country		= 'US';
	
	$paymentAmount 	= $objOrdersInfo->getAccount()->getAllTotal();;
	
	// Populate SOAP request information
	// Payment details
	$OrderTotal =& PayPal::getType('BasicAmountType');
	if (PayPal::isError($OrderTotal)) {
	    var_dump($OrderTotal);
	    exit;
	}
	
	$OrderTotal->setattr('currencyID', 'USD');
	$OrderTotal->setval($paymentAmount, 'iso-8859-1');
	$PaymentDetails =& PayPal::getType('PaymentDetailsType');
	$PaymentDetails->setOrderTotal($OrderTotal);
	
	$shipTo =& PayPal::getType('AddressType');
	$shipTo->setName($firstName.' '.$lastName);
	$shipTo->setStreet1($address1);
	$shipTo->setStreet2($address2);
	$shipTo->setCityName($city);
	$shipTo->setStateOrProvince($state);
	$shipTo->setCountry($country);
	$shipTo->setPostalCode($zip);
	$PaymentDetails->setShipToAddress($shipTo);
	
	$dp_details =& PayPal::getType('DoDirectPaymentRequestDetailsType');
	$dp_details->setPaymentDetails($PaymentDetails);
	
	// Credit Card info
	$card_details =& PayPal::getType('CreditCardDetailsType');
	$card_details->setCreditCardType($creditCardType);
	$card_details->setCreditCardNumber($creditCardNumber);
	$card_details->setExpMonth($expDateMonth);
	// $card_details->setExpMonth('01');
	$card_details->setExpYear($expDateYear);
	// $card_details->setExpYear('2010');
	$card_details->setCVV2($cvv2Number);
	$logger->_log('card_details: '. print_r($card_details, true));
	
	$payer =& PayPal::getType('PayerInfoType');
	$person_name =& PayPal::getType('PersonNameType');
	$person_name->setFirstName($firstName);
	$person_name->setLastName($lastName);
	$payer->setPayerName($person_name);
	
	$payer->setPayerCountry($country);
	$payer->setAddress($shipTo);
	
	$card_details->setCardOwner($payer);
	
	$dp_details->setCreditCard($card_details);
	$dp_details->setIPAddress($_SERVER['SERVER_ADDR']);
	$dp_details->setPaymentAction($paymentType);
	
	$dp_request->setDoDirectPaymentRequestDetails($dp_details);
	
	$caller =& PayPal::getCallerServices($profile);
	
	// Execute SOAP request
	$response = $caller->DoDirectPayment($dp_request);
	
	$ack = $response->getAck();
	
	$logger->_log('Ack='.$ack);
	
		
	switch($ack) {
	   case ACK_SUCCESS:
	   case ACK_SUCCESS_WITH_WARNING:
	      // Good to break out;
	      break;
	
	   default:
	      	$_SESSION['response'] =& $response;
	      	$logger->_log('DoDirectPayment failed: ' . print_r($response, true));
	      
			$location = HOME_URL . "/lib/paypal-app/ApiError.php";
	      	
	      	header("Location: $location");
	      	exit;
		}

		// Marshall data out of response
//	$details 		= $response->getDoExpressCheckoutPaymentResponseDetails();
//	$payment_info 	= $details->getPaymentInfo();
//	$tran_ID 		= $payment_info->getTransactionID();
//	$paymentStatus	= $payment_info->getPaymentStatus();
//	$paymentType	= $payment_info->getPaymentType();
//	
//	
//	$amt_obj		= $payment_info->getGrossAmount();
//	$amt 			= $amt_obj->_value;
//	$currency_cd 	= $amt_obj->_attributeValues['currencyID'];
//	$display_amt 	= $currency_cd.' '.$amt;
	
	//echo '$paymentAmount = ' . $paymentAmount . '<br>';
	//echo '$tran_ID = ' . $tran_ID . '<br>';
	//echo '$display_amt = ' . $display_amt . '<br>';
	
	$tran_ID 		= $response->getTransactionID();
	$avs_code 		= $response->getAVSCode();
	$cvv2 			= $response->getCVV2Code();
	$amt_obj 		= $response->getAmount();
	$paymentStatus 	= $response->getPaymentStatus();
	
	$amt 			= $amt_obj->_value;
	$currency_cd 	= $amt_obj->_attributeValues['currencyID'];
	$amt_display 	= $currency_cd.' '.$amt;
	
	$comments = $objOrdersInfo->getComments();
	if(!empty($comments)){
		$paymentResponse = "$comments\n";
	}
	
	$paymentResponse .= "Transaction ID: $tran_ID\n" . "Payment Type: Credit Card Direct Payment\nPayment Status: Completed " . $paymentStatus;
	
	$objOrdersDao->setCCOwner($objPaypalInfo->getCCFirstName() . ' ' . $objPaypalInfo->getCCLastName());
	$objOrdersDao->setCCType($objPaypalInfo->getCCType());
	$objOrdersDao->setCCNumber($payment->markCardNumber($objPaypalInfo->getCCNumber()));
	$objOrdersDao->setCCExpire($objPaypalInfo->getCCExpiresMonth() . '/' . $objPaypalInfo->getCCYear());
	
}else if($objOrdersInfo->getPaymentMethod() == OrdersInfo::MONEY_ORDER){
	$paymentMethod = "Money Order";
	
	$comments = $objOrdersInfo->getComments();
	if(!empty($comments)){
		$paymentResponse = "$comments\n";
	}
}

$oDeliveryAddress = $objOrdersInfo->getDeliveryAddress();

$customerAddress = $objOrdersInfo->getCustomerAddress();
if(!is_object($customerAddress)){
	$customerAddress = $oDeliveryAddress;
	
}

$billingAddress = $objOrdersInfo->getBillingAddress();
if(!is_object($billingAddress)){
	$billingAddress = $oDeliveryAddress;
}


$objOrdersDao->setCurrency($currency_cd);
$objOrdersDao->setLanguageID(1);
$objOrdersDao->setStatus('pending');
$objOrdersDao->setAmount($objOrdersInfo->getAccount()->getAllTotal() * 100);
$objOrdersDao->setComments($objOrdersInfo->getComments());
$objOrdersDao->setPaymentMethod($paymentMethod);

$sql_data_array = $objOrdersDao->getArray($objCustomer, $customerAddress, $oDeliveryAddress, $billingAddress);
// insert the data
$ordersid = $common->insertUpdate(DB_TAG_PUBLIC, 'orders', $sql_data_array);

// write orders account
$sql_data_array = array(
		'ordersID' 		=> $ordersid,
		'amount' 		=> $objOrdersInfo->getAccount()->getTaxTotal() * 100,
		'classes' 		=> "tax",
		'comments' 		=> "Sales Tax"
);
	
$common->insertUpdate(DB_TAG_PUBLIC, 'orders_account', $sql_data_array);


$sql_data_array = array(
		'ordersID' 		=> $ordersid,
		'amount' 		=> $objOrdersInfo->getAccount()->getShippingTotal() * 100,
		'classes' 		=> "shipping",
		'comments' 		=> "Shipping & Handling(Standard Shipping)"
);
	
$common->insertUpdate(DB_TAG_PUBLIC, 'orders_account', $sql_data_array);

$sql_data_array = array(
		'ordersID' 		=> $ordersid,
		'amount' 		=> $objCart->getAmount(),
		'classes' 		=> "product",
		'comments' 		=> "Subtotal"
);
	
$common->insertUpdate(DB_TAG_PUBLIC, 'orders_account', $sql_data_array);

$sql_data_array = array(
		'ordersID' 		=> $ordersid,
		'amount' 		=> $objOrdersInfo->getAccount()->getAllTotal() * 100,
		'classes' 		=> "total",
		'comments' 		=> "Total"
);
	
$common->insertUpdate(DB_TAG_PUBLIC, 'orders_account', $sql_data_array);

$sql_data_array = array(
		'ordersID' 		=> $ordersid,
		'status' 		=> 'pending',
		'createdTime' 	=> "UTC_TIMESTAMP()",
		'comments' 		=> $paymentResponse
);
	
$common->insertUpdate(DB_TAG_PUBLIC, 'orders_status_history', $sql_data_array);
// write orders account end;

// is partner traffic ?
if(isset($_COOKIE[PARTNER_COOKIE_NAME]) && is_numeric($_COOKIE[PARTNER_COOKIE_NAME])){
	$partnterID = $_COOKIE[PARTNER_COOKIE_NAME];
	
	$sql_data_array = array(
		'ordersID' 		=> $ordersid,
		'partnerID' 	=> $partnterID,
		'modifiedTime' 	=> "UTC_TIMESTAMP()"
	);
	
	$common->insertUpdate(DB_TAG_PUBLIC, 'orders_partner_history', $sql_data_array);
}

foreach($objCart->getProductList() as $product){
	$sql_data_array = array(
		'ordersID' 		=> $ordersid,
		'productsID' 	=> $product->getID(),
		'model' 		=> $product->getModel(),
		'name' 			=> $product->getName(),
		'price' 		=> $product->getPrice(),
		'finalPrice' 	=> $product->getFinalPrice(),
		'tax' 			=> 0,
		'quantity' 		=> $product->getQuantity(),
	);
	
	$insertID = $common->insertUpdate(DB_TAG_PUBLIC, 'orders_products', $sql_data_array);
	
	foreach($product->getAttributeList() as $attribute){
		$sql_data_array = array(
			'ordersID' 				=> $ordersid,
			'productID' 			=> $product->getID(),
			'attribute' 			=> $attribute->getKey(),
			'attributeValue' 		=> $attribute->getValue(),
			'attributeValuePrice' 	=> $attribute->getPrice(),
			'price_prefix' 			=> '+',
			'orderProdID'			=> $insertID
		);
		
		$common->insertUpdate(DB_TAG_PUBLIC, 'orders_products_attributes', $sql_data_array);
	}
}


// update coupon status
$oCoupon = $objCart->getCoupon();
if(is_object($oCoupon)){
	$common->update(DB_TAG_PUBLIC, 'UPDATE coupon SET usedCount = usedCount + 1 WHERE id = ' . $oCoupon->getID());
	
	$customerID = $objCustomer->getID();
	
	$common->insert(DB_TAG_PUBLIC, "INSERT INTO coupon_history SET customerID = $customerID, couponID = " . $oCoupon->getID());
}

$shippingTotal 	= $objOrdersInfo->getAccount()->getShippingTotal();
$subTotal 		= $objCart->getAmount() / 100;
$taxTotal		= $objOrdersInfo->getAccount()->getTaxTotal();
$allTotal		= $objOrdersInfo->getAccount()->getAllTotal();

$myStore	= $common->getRow(DB_TAG_PUBLIC, "SELECT c.title, c.values FROM configuration c, configuration_group g WHERE c.groupID=g.id AND g.title = 'My Store' AND c.keyes = 'STORE_NAME_ADDRESS'");

// send email to customer
$customerEmail = $objCustomerDao->getEmail();
if(!empty($customerEmail)){
	require_once('includeOrderNoticeEmail.php');
	
	
	$subject	= '123gohelmets.com - Order';
	
	/* To send HTML mail, you can set the Content-type header. */
	$headers  = "MIME-Version: 1.0\r\n";
	$headers .= "Content-type: text/html; charset=utf8\r\n";
	
	/* additional headers */
	$headers .= "From: Sam <123gohelmets@mail.com>\r\n";
	
	/* and now mail it */
	$siSuccess = mail($customerEmail, $subject, $emailContent, $headers);
	
//	if($siSuccess){
//    	$error_message = 'Success';
//	}else
//    	$error_message = 'Failed';
}

unset($_SESSION['cart']);
unset($_SESSION['customerInfo']);
unset($_SESSION['ordersInfo']);
unset($_SESSION['paypalInfo']);


/*----- out html -----*/
$smarty = new Smarty();	//-- out template
$smarty->template_dir 	= TEMPLATE_DIR;
$smarty->compile_dir  	= COMPILE_DIR;
$smarty->cache_dir  	= CACHE_DIR;

$smarty->force_compile 	= true;
$smarty->debugging 		= false;
$smarty->caching 		= false;
$smarty->cache_lifetime = 120;

$smarty->assign('HOME_URL', '.');
$smarty->assign('HOME_URL_HTTP', HOME_URL);

$smarty->assign('error_message', $error_message);


$smarty->assign('arrAddress', $arrAddress);
$smarty->assign('arrProducts', $arrProducts);

$smarty->assign('taxTotal', $taxTotal);
$smarty->assign('subTotal', $subTotal);
$smarty->assign('shippingTotal', $shippingTotal);
$smarty->assign('allTotal', $allTotal);

$smarty->assign('myStore', $myStore);


$smarty->assign('objCart', $objCart);
$smarty->assign('objStrings', $objStrings);
$smarty->assign('oDeliveryAddress', $oDeliveryAddress);

$smarty->assign('ordersid', $ordersid);
$smarty->assign('tran_ID', $tran_ID);

$smarty->assign('paymentMethod', $objOrdersInfo->getPaymentMethod());

$smarty->assign('isLogin', $isLogin);

$smarty->display('checkoutFinish.html');
?>
